//
// Timer.cs
//
// Copyright (c) 2007 Lukas Lipka.
//

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace IcqSharp.Util
{
    public class Timer
    {
        private Thread thread;        
        private int timeout;
        private DateTime end_time;
        private bool loop;
        private bool running;

        public event EventHandler Timeout;

        public Timer(int miliseconds)
        {
            this.timeout = miliseconds;

            this.thread = new Thread(new ThreadStart (DoWorker));
            this.thread.IsBackground = true;
            this.thread.Priority = ThreadPriority.BelowNormal;
        }

        public void Start()
        {
            if (running)
                return;

            end_time = DateTime.Now.AddMilliseconds (timeout);
            running = true;

            thread.Start();
        }

        public void Stop()
        {
            if (!running)
                return;

            running = false;
            thread.Join();
        }

        private void DoWorker()
        {
            while (running)
            {
                if (DateTime.Now > end_time)
                {
                    if (Timeout != null)
                        Timeout(this, EventArgs.Empty);

                    if (loop)
                    {
                        end_time = DateTime.Now.AddMilliseconds(timeout);
                    }
                    else
                    {
                        // We are not supposed to loop so bail out
                        running = false;
                        return;
                    }
                }
            }
        }

        public bool Loop
        {
            get { return loop; }
            set { loop = value; }
        }

        public bool Running
        {
            get { return running; }
        }
    }
}
